package com.icepeach.icepeachhomeback.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icepeach.icepeachhomeback.common.RelationEnum;
import com.icepeach.icepeachhomeback.config.ServiceAssert;
import com.icepeach.icepeachhomeback.dto.BindUserRoleDto;
import com.icepeach.icepeachhomeback.entity.Relation;
import com.icepeach.icepeachhomeback.entity.Role;
import com.icepeach.icepeachhomeback.mapper.RelationMapper;
import com.icepeach.icepeachhomeback.req.RoleListQueryReq;
import com.icepeach.icepeachhomeback.service.RoleService;
import com.icepeach.icepeachhomeback.mapper.RoleMapper;
import com.icepeach.icepeachhomeback.util.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 24273
 * @description 针对表【role】的数据库操作Service实现
 * @createDate 2023-05-03 21:22:36
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public IPage<Role> getRolesByPage(RoleListQueryReq roleListQueryReq) {

        IPage<Role> page = new Page<>(roleListQueryReq.getPageNum(), roleListQueryReq.getPageSize());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(roleListQueryReq.getName())) {
            queryWrapper.like("name", roleListQueryReq.getName());
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public ApiResult mySaveOrUpdate(Role role) {
        //新增
        if (StrUtil.isEmpty(role.getId())) {
            //校验简称是否重复
            Long name = baseMapper.selectCount(new QueryWrapper<Role>().eq("name", role.getName()));
            ServiceAssert.isTrue(name <= 0, "角色名称重复");
            //校验全称是否重复
            Long fullName = baseMapper.selectCount(new QueryWrapper<Role>().eq("full_name", role.getFullName()));
            ServiceAssert.isTrue(fullName <= 0, "角色全称重复");
            //校验编码是否重复
            Long code = baseMapper.selectCount(new QueryWrapper<Role>().eq("code", role.getCode()));
            ServiceAssert.isTrue(code <= 0, "编码重复");
            baseMapper.insert(role);
            return ApiResult.success("新增成功");
        } else {
            //校验简称是否重复
            Long name = baseMapper.selectCount(new QueryWrapper<Role>().eq("name", role.getName()).ne("id",role.getId()));
            ServiceAssert.isTrue(name <= 0, "角色名称重复");
            //校验全称是否重复
            Long fullName = baseMapper.selectCount(new QueryWrapper<Role>().eq("full_name", role.getFullName()).ne("id",role.getId()));
            ServiceAssert.isTrue(fullName <= 0, "角色全称重复");
            //校验编码是否重复
            Long code = baseMapper.selectCount(new QueryWrapper<Role>().eq("code", role.getCode()).ne("id",role.getId()));
            ServiceAssert.isTrue(code <= 0, "编码重复");
            baseMapper.updateById(role);
            return ApiResult.success("修改成功");

        }

    }

    @Override
    public ApiResult assignRole(BindUserRoleDto bindUserRoleDto) {
        Relation relation = new Relation();
        relation.setBusinessId(bindUserRoleDto.getUserId());
        relation.setBusinessName(bindUserRoleDto.getUserName());
        relation.setTargetId(bindUserRoleDto.getRoleId());
        relation.setTargetName(bindUserRoleDto.getRoleName());
        System.out.println(RelationEnum.USER_ROLE.getBusinessType());
        relation.setBusinessType(RelationEnum.USER_ROLE.getBusinessType());
        relation.setTargetType(RelationEnum.USER_ROLE.getTargetType());
        relationMapper.insert(relation);
        return ApiResult.success("成功");
    }

    @Override
    public ApiResult removeRole(BindUserRoleDto bindUserRoleDto) {
        relationMapper.deleteById(bindUserRoleDto.getId());
        return ApiResult.success("成功");
    }

    @Override
    public ApiResult<List<Role>> unBindRoleList(String userId) {
        if (null == userId){
            return ApiResult.success(new ArrayList<>());
        }
        List<Relation> bindRoles = relationMapper.queryRelationListByBusinessId(RelationEnum.USER_ROLE.getBusinessType(), RelationEnum.USER_ROLE.getTargetType(),
                userId);
        List<String> roleIds = bindRoles.stream().map(Relation::getTargetId).distinct().collect(Collectors.toList());
        List<Role> allRoles = roleMapper.selectList(new QueryWrapper<>());
        if (CollectionUtil.isNotEmpty(roleIds)){
            return ApiResult.success(allRoles.stream().filter(it -> !roleIds.contains(it.getId())).distinct().collect(Collectors.toList()));
        }else {
            return ApiResult.success(allRoles);
        }
    }

    @Override
    public ApiResult bindRoleList(String userId) {
        if (null == userId){
            return ApiResult.success(new ArrayList<>());
        }
        List<Relation> roles = relationMapper.queryRelationListByBusinessId(RelationEnum.USER_ROLE.getBusinessType(), RelationEnum.USER_ROLE.getTargetType(),
                userId);
        return ApiResult.success(roles);
    }
}
